package org.study.hadoop.md.ch2;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.study.hadoop.md.util.MRDPUtils;
/**
 * 数值概要1：对于给定的一个用户评论的列表，确定每个用户第一次和最近一次评论的时间以及这个用户所有的评论数。
 */
public class MinMaxCountDriver extends Configured implements Tool {
	
	public static class MinMaxCountReducer extends Reducer<Text, MinMaxCountTuple, Text, MinMaxCountTuple> {
		private MinMaxCountTuple result = new MinMaxCountTuple();
		
		@Override
		protected void reduce(Text key, Iterable<MinMaxCountTuple> values, Context context)
				throws IOException, InterruptedException {
			result.setMin(null);
			result.setMax(null);
			long sum = 0L;
			for (MinMaxCountTuple val : values) {
				if (result.getMin() == null || val.getMin().compareTo(result.getMin()) < 0) {
					result.setMin(val.getMin());
				}
				if (result.getMax() == null || val.getMax().compareTo(result.getMax()) > 0) {
					result.setMax(val.getMax());
				}
				sum += val.getCount();
			}
			result.setCount(sum);
			context.write(key, result);
		}
	}
	
	public static class MinMaxCountMapper extends Mapper<Object, Text, Text, MinMaxCountTuple> {
		private Text outUserId = new Text();
		private MinMaxCountTuple outTuple = new MinMaxCountTuple();
		
		private final static SimpleDateFormat FRMT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		@Override
		protected void map(Object key, Text value, Context context)
				throws IOException, InterruptedException {
			Map<String, String> parsed = MRDPUtils.transformXmlToMap(value.toString());
			String strDate = parsed.get("CreationDate");
			String userId = parsed.get("UserId");
			try {
				Date creationDate = FRMT.parse(strDate);
				outTuple.setMin(creationDate);
				outTuple.setMax(creationDate);
				outTuple.setCount(1L);
				outUserId.set(userId);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			context.write(outUserId, outTuple);
		}
	}
	
	public static class MinMaxCountTuple implements Writable {
		private Date min = new Date();
		private Date max = new Date();
		private Long count = 0L;
		
		public final static SimpleDateFormat FRMT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		public Date getMin() {
			return min;
		}
		public void setMin(Date min) {
			this.min = min;
		}
		public Date getMax() {
			return max;
		}
		public void setMax(Date max) {
			this.max = max;
		}
		public Long getCount() {
			return count;
		}
		public void setCount(Long count) {
			this.count = count;
		}

		@Override
		public void write(DataOutput out) throws IOException {
			out.writeLong(min.getTime());
			out.writeLong(max.getTime());
			out.writeLong(count);
		}

		@Override
		public void readFields(DataInput in) throws IOException {
			min = new Date(in.readLong());
			max = new Date(in.readLong());
			count = in.readLong();
		}
		
		@Override
		public String toString() {
			return FRMT.format(min) + "\t" + FRMT.format(max) + "\t" + count;
		}
	}

	@Override
	public int run(String[] args) throws Exception {
		Path outPath = new Path("out");
		Path inPath = new Path("comment.txt");
		FileSystem fs = outPath.getFileSystem(getConf());
		if (fs.exists(outPath)) {
			fs.delete(outPath, true);
		}
		Job job = Job.getInstance(getConf());
		job.setJarByClass(MinMaxCountDriver.class);
		job.setMapperClass(MinMaxCountMapper.class);
		job.setCombinerClass(MinMaxCountReducer.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(MinMaxCountTuple.class);
		FileInputFormat.addInputPath(job, inPath);
		FileOutputFormat.setOutputPath(job, outPath);
		return job.waitForCompletion(true) ? 0 : 1;
	}
	
	public static void main(String[] args) throws Exception {
		int res = ToolRunner.run(new Configuration(), new MinMaxCountDriver(), args);
		System.exit(res);
	}
}
